/* =========================================
 *      语音识别子服务的客户端测试搭建 
 * =========================================*/


#include "aip-cpp-sdk/speech.h"     // 必须先包含speech.h, 其内部transform包含了cytpe.h的接口, 并且没有指明作用域
#include "etcd.hpp"                 // 如果在后面包含, 会先引入<cctype>, 进而识别不出transform中使用的接口所在位置
#include "channel.hpp"
#include "speech_recognition.pb.h"
#include <chrono>
#include <gflags/gflags.h>
#include <string>
#include <thread>

DEFINE_bool(run_mode, false, "程序的运行模式: false-调试 true-发布");
DEFINE_string(log_file, "", "指定日志的输出文件");
DEFINE_int32(log_level, 0, "指定日志输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(speech_service, "/service/speech_service", "当前监控的服务");

int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    shared::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    // 1.构造rpc服务管理对象
    shared::infra::RpcServiceManagerPtr serviceManager = std::make_shared<shared::infra::RpcServiceManager>();
    serviceManager->declared(FLAGS_speech_service);   
    auto putCb = std::bind(
        &shared::infra::RpcServiceManager::onServiceOnline, serviceManager.get(), std::placeholders::_1, std::placeholders::_2
    );
    auto delCb = std::bind(
        &shared::infra::RpcServiceManager::onServiceOffline, serviceManager.get(), std::placeholders::_1, std::placeholders::_2
    );

    // 2.构造服务发现对象
    shared::infra::DiscoveryPtr client = std::make_shared<shared::infra::Discovery>(
        FLAGS_etcd_host, FLAGS_base_service, putCb, delCb
    );

    // 3.获取该服务的rpc信道对象
    shared::infra::RpcServiceChannel::ChannelPtr channel = serviceManager->choose(FLAGS_speech_service);
    if(!channel) {
        return 1;
    }

    // 4. 读取语音文件数据
    std::string fileContent;
    aip::get_file_content("16k.pcm", &fileContent);

    // 4.构造EchoService_Stub对象，用于rpc调用
    im_proto::SpeechService_Stub stub(channel.get());
    im_proto::SpeechRecognitionReq req;
    req.set_request_id("2025-07-12 19:28:32");
    req.set_speech_content(fileContent);
    brpc::Controller* controller = new brpc::Controller();
    im_proto::SpeechRecognitionRsp* resp = new im_proto::SpeechRecognitionRsp();
    
    // 4-1 同步调用
    stub.SpeechRecognition(controller, &req, resp, nullptr);     
    if (controller->Failed() == true) {
        std::cout << "rpc调用失败: " << controller->ErrorText() << std::endl;
        delete controller;
        delete resp;
        return 2;
    }
    if(!resp->success()) {
        std::cout << "语音识别失败: " << resp->errmsg() << "\n";
        return 3;
    }

    std::cout << "响应ID: " << resp->request_id() << "\n";
    std::cout << "响应内容: " << resp->recognition_result() << "\n";
    delete controller;
    delete resp;
    return 0;
}